package com.yunyike.controller.address;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.model.Recepient;
import com.yunyike.model.User;
import com.yunyike.response.Response;
import com.yunyike.service.IRecepientService;
import com.yunyike.service.IRegionService;

/**
 * @author zhengqiang.shi
 * 2015年11月26日 下午10:29:51
 */
@Controller
@RequestMapping(value=RequestConstant.ADDRESS)
public class AddressController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(AddressController.class);
	
	@Autowired
	private IRecepientService recepientService;
	
	@Autowired
	private IRegionService regionService;
	
	/**
	 * 获取默认收货地址
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.ADDRESS_DEFAULT)
	public void getDefault(HttpServletResponse response){
		// 当前用户信息
		User user = getCurrentUser();
		
		Response res = new Response();
		
		List<Recepient> list = null;
		try {
			list = recepientService.findRecepientByUser(user.getUserId());
		} catch (Exception e) {
			log.error("recepientService.findRecepientByUser has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		if(list == null || list.isEmpty()){
			log.info("no recepient by current user.");
			returnDatas(res, response);
			return;
		}
		
		Recepient recepient = findDefault(list);
		
		res.setData(recepient);
		returnDatas(res, response);
		
	}
	
	private Recepient findDefault(List<Recepient> list){
		
		for (Recepient recepient : list) {
			if(recepient.getIsDefault() == CommonConstant.NUMBER_1){
				log.info("has default address.{}",recepient);
				return recepient;
			}
		}
		log.info("not found default address.return first.");
		return list.get(0);
	}
	
	/**
	 * 根据用户查询地址信息
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.ADDRESS_LIST)
	public void findByUser(HttpServletResponse response){
		
		Response res = new Response();
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		List<Recepient> list;
		try {
			list = recepientService.findRecepientByUser(user.getUserId());
		} catch (Exception e) {
			log.error("address.list recepientService.findRecepientByUser has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		res.setData(list);
		returnDatas(res, response);
	}
	
	/**
	 * 修改或者添加收货地址
	 */
	@RequestMapping(value=RequestConstant.ADDRESS_UPDATE,method=RequestMethod.POST)
	public void updateAddress(Model model,@Validated Recepient recepient,
			HttpServletResponse response, BindingResult br){
		
		log.info("update recepient by id...,recepient:"+recepient);
		Response res = new Response();
		
		checkRequest(br, res, response);
		
		if(br.hasErrors()){
			return;
		}
		
		// 当前用户信息
		User user = getCurrentUser();
		
		String recepientId = recepient.getRecepientId();
		
		int result = 0;
		
		// 设置省市区的名称
		recepient.setRecepientProvinceName(regionService.findProvinceName(recepient.getRecepientProvinceId()));
		recepient.setRecepientCityName(regionService.findCityName(recepient.getRecepientCityId()));
		recepient.setRecepientAreaName(regionService.findProvinceName(recepient.getRecepientAreaId()));
		
		// 添加
		if(StringUtils.isBlank(recepientId)){
			log.info("add recepient...");
			recepient.setRecepientId(UUID.randomUUID().toString());
			recepient.setIsDefault(CommonConstant.NUMBER_0);
			recepient.setUserId(user.getUserId());
			recepient.setRecepientStatus(CommonConstant.NUMBER_1);
			result = recepientService.addRecepient(recepient);
		}else{ // 更新
			// 收货地址信息
			List<Recepient> list = recepientService.findRecepientByUser(user.getUserId());
			
			// 安全验证
			Recepient recepientDB = checkRecepient(list,recepientId);
			if(recepientDB == null){
				log.error("update failed.because this recepient is not for current user.recepientId:"+recepientId+"\tuserId:"+user.getUserId());
				res.getResult().setCode(CommonConstant.NUMBER__1);
				res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__1));
				returnDatas(res, response);
				return;
			}else{
				log.info("update recepient...");
				result = recepientService.updateRecepient(recepient);
			}
		}
		
		log.info("updateAddress end.result:"+result);

		if(result != CommonConstant.NUMBER_1){
			log.info("update or add recepient end.but result isn't 1. set default recepient failed.");
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		returnDatas(res, response);
		
	}
	
	/**
	 * 删除收货地址
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.ADDRESS_REMOVE+"/{recepientId}",method=RequestMethod.POST)
	public void removeAddress(Model model,@PathVariable String recepientId,
			HttpServletRequest request,HttpServletResponse response){
		
		log.info("remove recepient by id...,recepientId:"+recepientId);
		
		Response res = new Response();
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		List<Recepient> list;
		try {
			list = recepientService.findRecepientByUser(user.getUserId());
		} catch (Exception e) {
			log.error("address.remove findRecepientByUser has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		// 安全验证
		Recepient recepientDB = checkRecepient(list,recepientId);
		if(recepientDB == null){
			log.error("this address is not for current user.userId:"+user.getUserId());
			res.getResult().setCode(CommonConstant.NUMBER__1);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__1));
			returnDatas(res, response);
			return;
		}
		
		log.info("remove recepient...");
		recepientDB.setRecepientStatus(CommonConstant.NUMBER_0);
		int result;
		try {
			result = recepientService.updateRecepient(recepientDB);
		} catch (Exception e) {
			log.error("address.remove updateRecepient has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		log.info("remove recepient end.result:"+result);
		if(result != CommonConstant.NUMBER_1){
			log.info("remove recepient end.but result isn't 1. set default recepient failed.");
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		returnDatas(res, response);
	}
	
	/**
	 * 设置默认收货地址
	 * @param addressId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.ADDRESS_SET_DEFAULT+"/{addressId}",method=RequestMethod.POST)
	public void setDefaultAddress(@PathVariable String addressId,
			HttpServletResponse response){
		
		log.info("set default recepient...,addressId:"+addressId);
		
		Response res = new Response();
		
		// 当前用户信息
		User user = getCurrentUser();
		
		// 收货地址信息
		List<Recepient> list;
		try {
			list = recepientService.findRecepientByUser(user.getUserId());
		} catch (Exception e) {
			log.error("address.setdefault findRecepientByUser has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		// 安全验证
		Recepient recepient = checkRecepient(list,addressId);
		if(recepient == null){
			log.error("this address is not for current user.userId:"+user.getUserId());
			res.getResult().setCode(CommonConstant.NUMBER__1);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__1));
			returnDatas(res, response);
			return;
		}
		
		// 设置默认收货地址
		recepient.setIsDefault(CommonConstant.NUMBER_1);
		int result;
		try {
			result = recepientService.setDefaultRecepient(recepient);
		} catch (Exception e) {
			log.error("address.setdefault findRecepientByUser has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		if(result != CommonConstant.NUMBER_1){
			log.info("set default recepient end.but result isn't 1. set default recepient failed.");
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		returnDatas(res, response);
		
	}
	
	private Recepient checkRecepient(List<Recepient> list, String addressId){
	
		if(list == null || list.isEmpty()){
			log.info("checkRecepient return null,because list was empty.");
			return null;
		}
		
		for (Recepient recepient : list) {
			
			if(recepient.getRecepientId().equals(addressId)){
				log.info("checkRecepient return recepient.");
				return recepient;
			}
		}
		log.info("checkRecepient return null,match failed.");
		return null;
	}
}
